<template>
    <div
        class="shade-bg"
        v-show="isOpen"
    >
        <div class="img">
            <img src="../asset/icon/icon_loading_w.png" />
            <p>{{msg}}</p>
        </div>
    </div>
</template>

<script>
import * as qiniu from 'qiniu-js'

export default {
    name: 'qiniu-upload',
    props: {},
    data() {
        return {
            // 状态
            isOpen: false,
            msg: '上传中...',
            // form upload config
            observable: {},
            subscription: {},
            token: '',
            domain: '',
            config: {
                useCdnDomain: false,
                region: null
            },
            // 上传数据
            files: [],
            total: 0,
            current: 0,
            // 返回值
            result: [],
            fn: []
        }
    },
    methods: {
        getQiniuToken: function () {
            this.$post('/api/upload/qiniuToken').then((res) => {
                if (res.code === 20000) {
                    this.token = res.data.qiniu_token
                } else {
                    console.log(res.msg)
                }
            }).catch((res) => {
                console.log(res)
            })
        },
        qiniuUpload: function (files, fun) {
            this.result = []
            this.isOpen = true
            this.files = files
            this.total = files.length
            this.fn = fun
            this.qiniuloop()
        },
        qiniuloop: function () {
            if (this.current < this.total) {
                this.formDataUpload(this.files[this.current])
            } else {
                this.callBack()
            }
        },
        formDataUpload: function (file) {
            let putExtra = {
                fname: file.name,
                params: {},
                mimeType: null
            }
            this.observable = qiniu.upload(file, null, this.token, putExtra, this.config)
            this.subscription = this.observable.subscribe((res) => {
                console.log(res.total.percent)
            }, (err) => {
                console.log(err)
            }, (res) => {
                this.result.push(res)
                this.current++
                this.qiniuloop()
            })
        },
        qiniuCancel: function () {
            // 上传取消
            this.subscription.unsubscribe()
        },
        callBack: function () {
            this.fn(this.result)
            this.isOpen = false
        }
    },
    watch: {
    },
    created() {
        this.getQiniuToken()
    }
}
</script>

<style scoped>
</style>
